﻿using System;
using System.Globalization;
using System.Windows.Forms;
using Matrix.MaKaYunShang.QrCodeCreator.Properties;

namespace Matrix.MaKaYunShang.QrCodeCreator
{
    public partial class CreatorForm : Form
    {
        public QrCodeCreateThread QrCreateThread;

        public CreatorForm()
        {
            InitializeComponent();
            InitializeEnvironment();
        }

        public void InitializeEnvironment()
        {
            btnCreator.Enabled = true;
            btnStop.Enabled = false;
            progressBarCreator.Value = 0;
        }

        public void CreateThread_OnEventFinishedQrCode(object sender, EventArgs e)
        {
            Invoke((EventHandler)(delegate
            {
                lbCreatedAmount.Text = ((QrCodeCreateThread)sender).NFinishCreateAmount.ToString(CultureInfo.InvariantCulture);
                var runflag = ((QrCodeCreateThread) sender).BRunning;
                btnCreator.Enabled = !runflag;
                btnStop.Enabled = runflag;
                progressBarCreator.Value = ((QrCodeCreateThread) sender).NFinishCreateAmount;
            }));
        }

        private void btnCreator_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtWaitToCreateAmount.Text) || string.IsNullOrWhiteSpace(txtWechatId.Text))
            {
                MessageBox.Show(Resources.EmptyParameters);
                return;
            }

            int nTotalAmount;
            if (!int.TryParse(txtWaitToCreateAmount.Text, out nTotalAmount))
            {
                MessageBox.Show(Resources.InvalidParamters);
                return;
            }

            int nStartSceneId;
            if (!int.TryParse(txtStartSceneId.Text, out nStartSceneId))
            {
                MessageBox.Show(Resources.InvalidParamters);
                return;
            }
            nStartSceneId = nStartSceneId > 100000 ? 100000 : nStartSceneId;

            progressBarCreator.Value = 0;
            progressBarCreator.Maximum = nTotalAmount;


            QrCreateThread = new QrCodeCreateThread(nTotalAmount, false, txtWechatId.Text, nStartSceneId);
            QrCreateThread.OnEventFinishedQrCode +=
                CreateThread_OnEventFinishedQrCode;
            
            QrCreateThread.CreateNewThread();
            QrCreateThread.StartThread();
            btnCreator.Enabled = false;
            btnStop.Enabled = true;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            QrCreateThread.StopThread();
            btnCreator.Enabled = true;
            btnStop.Enabled = false;
        }
    }
}
